<template>
  <div style="width: 100%">
    <el-form ref="form"
             :model="formData"
             :rules="rules"
             :disabled="dialogType==='view'"
             label-width="130px"
             size="small">
      <el-collapse v-model="active">
        <el-collapse-item title="基本配置" :name="1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="模板名称" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板编码" prop="name">
                <el-input :disabled="dialogType!=='open'" v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="接受者">
                <el-radio-group v-model="formData.receiveType"
                                @change="changeReceiveType">
                  <el-radio :label="1">用户</el-radio>
                  <el-radio :label="2">邮箱</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="时间">
                <el-radio-group v-model="formData.sendType">
                  <el-radio :label="1">立即</el-radio>
                  <el-radio :label="2">定时</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="选择用户" prop="receiver" v-if="formData.receiveType===1">
                <el-select v-model="formData.receiver" multiple style="width: 100%">
                  <template v-for="item in userList">
                    <el-option :value="item.pid" :label="item.username"></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="邮箱(逗号隔开)" prop="receiver" v-else>
                <el-input v-model="formData.receiver"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.sendType === 2">
              <el-form-item label="定时表达式">
                <ms-cron-input :value.sync="formData.expectPushTime"></ms-cron-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item title="渠道信息" :name="2">
          <el-row>
            <el-col :span="24">
              <el-form-item label="发送至" prop="templateRefListOID">
                <el-checkbox-group v-model="formData.templateRefListOID"
                                   @change="changeTemplateRef">
                  <template v-for="item in channelList">
                    <el-checkbox :label="item.oid">{{ item.name }}</el-checkbox>
                  </template>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发送策略">
                <el-radio-group v-model="formData.sendPolicy">
                  <el-radio :label="1">渠道全发</el-radio>
                  <el-radio :label="2">只发一条（失败尝试下一渠道）</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.templateRefList.length>0">
            <el-col :span="24">
              <el-form-item label="模板内容">
                <draggable :list="formData.templateRefList" tag="div" class="tabs-temp"
                           :group="{name: 'channel',pull:true, put: true}">
                  <template v-for="item in formData.templateRefList">
                    <div class="tabs-temp-header" :class="{'tabs-temp-header-active':activeTabs === item.sendAccountId}"
                         @click.stop.prevent="activeTabs = item.sendAccountId">
                      {{ item.name || item.channelName }}
                    </div>
                  </template>
                </draggable>
                <template v-for="item in formData.templateRefList">
                  <template v-if="formData.receiveType === 1">
                    <el-input type="textarea"
                              v-show="activeTabs === item.sendAccountId"
                              :rows="5"
                              v-model="item.templateVariables"
                              resize="none"
                              placeholder="请输入模板内容……">
                    </el-input>
                  </template>
                  <template v-else>
                    <el-input v-show="activeTabs === item.sendAccountId" placeholder="请输入标题"
                              v-model="item.templateVariables.subject"></el-input>
                    <el-input v-show="activeTabs === item.sendAccountId" placeholder="请输入内容"
                              v-model="item.templateVariables.text"
                              type="textarea" rows="5" resize="none"></el-input>
                  </template>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" @click="save" v-if="dialogType!=='view'">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>
  </div>
</template>

<script>
import * as channel from "@/api/notification/channel";
import Draggable from "vuedraggable";

import * as temp from "@/api/notification/template"
import MsCronInput from "@/components/ms-cron/ms-cron-input.vue";

export default {
  name: "notificationTemplateTemp",
  components: {MsCronInput, Draggable},
  data() {
    return {
      active: [1, 2],
      formData: {
        name: "",
        receiver: "",
        nameCn: "",
        receiveType: 1,
        sendType: 1,
        sendPolicy: 1,
        expectPushTime: "* * * * * ? *",
        templateRefList: [],
        templateRefListOID: []
      },

      rules: {
        name: [
          {required: true, message: "请输入编码", trigger: "blur"},
          {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}
        ],
        nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
        receiver: [{required: true, message: "请选择用户", trigger: "change"}],
        templateRefListOID: [{required: true, message: "请选择发送渠道", trigger: "change"}],
      },

      channelListSource: [],

      activeTabs: "",

      dialogType: "open",

      userList: []
    }
  },
  computed: {
    channelList() {
      return this.channelListSource.filter(i => {
        Object.assign(i, {sendAccountId: i.oid});
        return i.enableFlag === 1 && i.sendChannel === this.formData.receiveType
      });
    }
  },
  methods: {
    changeReceiveType(v) {
      this.formData.templateRefList = [];
      this.formData.templateRefListOID = [];
      let receiver = this.rules.receiver
      Object.assign(receiver[0], {message: v === 1 ? "请选择用户" : "请输入邮箱", trigger: v === 1 ? "change" : "blur"})
      this.rules.receiver = receiver;
      this.formData.receiver = v === 1 ? [] : "";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      })
    },
    getUserList() {
      temp.getUser().then((res) => {
        this.userList = res.data.data;
      })
    },
    save() {
      this.$refs["form"].validate(f => {
        if (f) {
          for (let i = 0; i < this.formData.templateRefList.length; i++) {
            let item = this.formData.templateRefList[i];
            Object.assign(this.formData.templateRefList[i], {sort: i});
            if (this.formData.receiveType === 1) {
              if (!item.templateVariables) {
                this.activeTabs = item.sendAccountId;
                this.$message.warning("请输入模板内容")
                return;
              }
            }
          }

          let form = this.deepCopy(this.formData);
          if (form.receiveType === 1) {
            form.receiver = form.receiver.join(",")
          } else {
            form.templateRefList.forEach(item => {
              item.templateVariables = JSON.stringify(item.templateVariables);
            })
          }


          let methods = this.dialogType === "edit" ? "update" : "add"
          temp[methods](form).then(() => {
            this.$message.success("保存成功");
            this.$emit('refresh');
            this.$emit('removeThisTabs');
          })
        }
      })
    },
    open() {
      this.dialogType = "open";
      this.getChannel();
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      })
    },
    edit(row) {
      this.dialogType = "edit";
      this.getDetail(row)
    },
    view(row) {
      this.dialogType = "view";
      this.getDetail(row)
    },
    getDetail(row) {
      temp.detail({oid: row.oid}).then(res => {
        let data = res.data.data;
        this.formData.templateRefListOID = data.templateRefList.map(i => {
          if (i.enableFlag === 1) {
            return i.sendAccountId
          }
        });
        Object.assign(this.formData, data);
        if (data.receiveType === 2) {
          data.templateRefList.forEach(item => {
            item.templateVariables = JSON.parse(item.templateVariables);
          })
        }
        this.$set(this.formData, "templateRefList", data.templateRefList);

        if (data.receiveType === 1) {
          this.formData.receiver = data.receiver.split(",");
        }
        let receiver = this.rules.receiver
        Object.assign(receiver[0], {
          message: data.receiveType === 1 ? "请选择用户" : "请输入邮箱",
          trigger: data.receiveType === 1 ? "change" : "blur"
        })
        this.rules.receiver = receiver;

        this.$refs["form"].clearValidate();

        this.activeTabs = data.templateRefList[0].sendAccountId;
        this.getChannel();
      })
    },
    changeTemplateRef(value) {
      if (this.formData.templateRefList.length === 0) {
        this.channelList.forEach(item => {
          if (value.includes(item.sendAccountId)) {
            this.formData.templateRefList.push({
              name: item.name,
              templateVariables: this.formData.receiveType === 1 ? "" : {"subject": "", "text": ""},
              enableFlag: 1,
              sendAccountId: item.sendAccountId
            })
          }
        })
      } else {
        let templateRefList = this.deepCopy(this.formData.templateRefList);
        this.formData.templateRefList = [];
        let activeList = this.channelList.filter(i => value.includes(i.sendAccountId));
        //渠道添加时
        let ids = templateRefList.map(item => item.sendAccountId);
        activeList.forEach(item => {
          if (!ids.includes(item.oid)) {
            templateRefList.push({
              name: item.name,
              enableFlag: 1,
              templateVariables: this.formData.receiveType === 1 ? "" : {"subject": "", "text": ""},
              sendAccountId: item.sendAccountId
            });
          }
        })
        //渠道减少时
        ids = activeList.map(item => item.sendAccountId);
        templateRefList.forEach(item => {
          if (ids.includes(item.sendAccountId)) {
            this.formData.templateRefList.push(item)
          }
        })
      }
      this.activeTabs = this.formData.templateRefList.length > 0 ? this.formData.templateRefList[0].sendAccountId : "";
    },
    getChannel() {
      channel.list({enableFlag: "1"}).then(res => {
        this.channelListSource = res.data.data;
      })
    }
  },
  mounted() {
    this.getUserList();
  }
}
</script>

<style scoped lang="scss">
.tabs-temp {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;

  .tabs-temp-header {
    cursor: pointer;
    border-bottom: 3px solid rgba(0,0,0,0);
  }

  .tabs-temp-header + .tabs-temp-header {
    margin-left: 20px;
  }

  .tabs-temp-header-active {
    border-bottom: 3px solid #409EFF;
  }
}
</style>
